package com.nuanshui.heatedloan.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletContext;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件存储服务类
 */
public class StorageService {

	private final ServletContext servletContext;

	private final String paperFileName;

	/**
	 * 文件上传的根目录，常量
	 */
	public static String UPLOAD_ROOT = "uploads";

	private static final SimpleDateFormat FMT_FN = new SimpleDateFormat(
			"yyyyMM/ddHHmmss_");

	/**
	 * 根据文件类型，将文件放在不同的文件夹中
	 */
	public final static StorageService IMAGES = new StorageService("images");

	/**
	 * 通过excel导入客户，存放用户上传的excel
	 */
	public final static StorageService EXCEL = new StorageService("excel");

	private final String file_path;

	/**
	 * 构造方法，用于设置
	 * 
	 * @param ext
	 */
	private StorageService(final String ext) {
		this.paperFileName = ext;
		servletContext = null;
		String root = servletContext.getRealPath(UPLOAD_ROOT);
		root = new StringBuilder(root).append(File.separator).append(paperFileName).append(File.separator).toString();
		this.file_path = root;
	}

	public FileInputStream read(final String path) throws FileNotFoundException {
		return new FileInputStream((new StringBuilder()).append(getBasePath())
				.append(path).toString());
	}

	public File readFile(final String path) throws FileNotFoundException {
		return new File((new StringBuilder()).append(getBasePath())
				.append(path).toString());
	}

	public boolean exist(final String path) {
		return (new File((new StringBuilder()).append(getBasePath())
				.append(path).toString())).exists();
	}

	public String save(final File f) throws IOException {
		final String uri = (new StringBuilder())
				.append(FMT_FN.format(new Date()))
				.append(RandomStringUtils.randomAlphanumeric(4)).append('.')
				.append(FilenameUtils.getExtension(f.getName()).toLowerCase())
				.toString();
		return save(f, uri);
	}
	
	/**
	 * 图片进行base64编码的上传方法
	 * @param base64EncodeStr
	 * @param ext
	 * @return
	 * @throws IOException
	 */
	public String save(final String base64EncodeStr, final String ext) throws IOException {
		return null;
	}

	public String save(final MultipartFile m) throws IOException {
		if (m.isEmpty()) {
			throw new IOException("MultipartFile must not null");
		} else {
			final String uri = (new StringBuilder())
					.append(FMT_FN.format(new Date()))
					.append(RandomStringUtils.randomAlphanumeric(4))
					.append('.')
					.append(m.getOriginalFilename().split("\\.")[1]
							.toLowerCase()).toString();
			return save(m.getInputStream(), uri);
		}
	}

	public String save(final File f, final String path) throws IOException {
		final File dest = new File((new StringBuilder()).append(getBasePath())
				.append(path).toString());
		if (!dest.getParentFile().exists())
			dest.getParentFile().mkdirs();
		FileUtils.copyFile(f, dest);
		return path;
	}
	
	public String saveBytes(final byte[] bytes, final String path) throws IOException {
		final File dest = new File((new StringBuilder()).append(getBasePath())
				.append(path).toString());
		if (!dest.getParentFile().exists())
			dest.getParentFile().mkdirs();
		final OutputStream out = new FileOutputStream(dest);
		out.write(bytes);
		out.flush();
		out.close();
		return new StringBuilder().append(UPLOAD_ROOT).append("/").append(path).toString();
	}
	
	public String save(final InputStream inputStream, final String path)
			throws IOException {
		final File dest = new File((new StringBuilder()).append(getBasePath())
				.append(File.separator).append(getPaperFileName())
				.append(File.separator).append(path).toString());
		if (!dest.getParentFile().exists())
			dest.getParentFile().mkdirs();
		FileUtils.copyInputStreamToFile(inputStream, dest);
		inputStream.close();
		return (new StringBuilder()).append(getPaperFileName()).append("/")
				.append(path).toString();
	}

	public void delete(final String path) throws IOException {
		if (path.endsWith("jpg") || path.endsWith("JPG")
				|| path.endsWith("png") || path.endsWith("PNG")
				|| path.endsWith("bmp") || path.endsWith("BMP")
				|| path.endsWith("gif") || path.endsWith("GIF")) {
			final File dest = new File((new StringBuilder())
					.append(getBasePath()).append(path).toString());
			FileUtils.forceDelete(dest);
		}
	}

	public String getBaseUri() {
		return (new StringBuilder()).append("/uploads/")
				.append(getPaperFileName()).append("/").toString();
	}

	public String getRealPath(final String path) {
		return (new StringBuilder()).append(getBasePath())
				.append(File.separator).append(path).toString();
	}

	/**
	 * 获得文件存储的根路径/位置 uploads
	 */
	protected String getBasePath() {
		return file_path;
	}

	/**
	 * 获得文件类型存储路径 images
	 * 
	 * @return
	 */
	protected String getPaperFileName() {
		return paperFileName;
	}

}
